import React, { PureComponent as Component } from 'react';
import PropTypes from 'prop-types';
import {
  Table,
  // Button,
  // Tooltip, Icon,
  DatePicker, Select, Button
  // , Button
} from 'antd';
const {Option} = Select;
// import axios from 'axios';
// import variable from '../../../../constants/variable';
import { connect } from 'react-redux';
// const Option = Select.Option;
import { fetchMethodListMenu } from '../../../../reducer/modules/dubboMethod.js';
import moment from "moment";

@connect(
  state => {
    return {
      dubboProjectList: state.dubboProject.dubboProjectList,
      list: state.dubboMethod.list
    };
  },
  {
    fetchMethodListMenu
  }
)
export default class ImportInterface extends Component {
  constructor(props) {
    super(props);
  }

  state = {
    // TTC ADD
    onlinedate:null,
    status:null,
    isapi:null,
    methodList:[],  // 存储当前要展示的方法数据
    data:[],        // 存储当前的所有方法数据
    // ^^^^^
    selectedRowKeys: [],
    infCount: {},
    project: this.props.currProjectId,
    searchText: ''
  };

  static propTypes = {
    list: PropTypes.array,
    selectMethod: PropTypes.func,
    dubboProjectList: PropTypes.array,
    currProjectId: PropTypes.string,
    fetchMethodListMenu: PropTypes.func,
    form: PropTypes.object
  };


  async componentDidMount() {
    await this.props.fetchMethodListMenu(this.props.currProjectId);
    const { list } = this.props;
    const methodList = [];
    const infData = list.map(item => {
      return {
        key: 'inf_' + item._id,
        classname: item.classname,
        cname: item.cname,
        isInf: true,
        children: item.list
          ? item.list.map(e => {
            e.key = e._id;
            e.infKey = 'inf_' + item._id;
            e.infLength = item.list.length;
            e.classname = item.classname;
            return e;
          })
          : []
      };
    });
    infData.map(item => {
      item.children.map(e => {
        methodList.push(e)
      })
    });

    this.setState({
      methodList:methodList,
      data:methodList
    })

  }

  // 切换项目
  onChange = async val => {
    this.setState({
      project: val,
      selectedRowKeys: [],
      infCount: {}
    });
    await this.props.fetchMethodListMenu(val);
  };

  // TTC ADD
  handleDateChange = (onlinedateTS) => {
    if(onlinedateTS === null){
      this.setState({
        onlinedate:null
      })
    }
    else {
      let onlinedate = moment(onlinedateTS).format('YYYY-MM-DD');
      this.setState({
        onlinedate: onlinedate
      })
    }
  };
  handleApiChange = (isapi) => {
    this.setState({
      isapi:isapi
    })
  };
  handleStatusChange = (status) => {
    this.setState({
      status:status
    })
  };

  handleSearch = () => {
    let onlinedate = this.state.onlinedate;
    let status = this.state.status;
    let isapi = this.state.isapi;
    let list = [];
    let data = this.state.data;
    // onlinedate status isapi
    if(onlinedate && status !== null && isapi !== null){
      for(let i=0; i<data.length; i++){
        if (data[i].status === status && data[i].onlinedate === onlinedate && data[i].isapi === isapi){
          list.push(data[i])
        }
      }
      this.setState({
        methodList: list
      })
    }
    // onlinedate
    else if(onlinedate && status === null && isapi === null){
      for(let i=0; i<data.length; i++){
        if (data[i].onlinedate === onlinedate){
          list.push(data[i])
        }
      }
      this.setState({
        methodList: list
      })
    }
    // status
    else if(!onlinedate && status !== null && isapi === null){
      for(let i=0; i<data.length; i++){
        if (data[i].status === status){
          list.push(data[i])
        }
      }
      this.setState({
        methodList: list
      })
    }
    // isapi
    else if(!onlinedate && status === null && isapi !== null){
      for(let i=0; i<data.length; i++){
        if(data[i].isapi === isapi){
          list.push(data[i])
        }
      }
      this.setState({
        methodList:list
      })
    }
    // onlinedate status
    else if(onlinedate && status !== null && isapi === null){
      for(let i=0; i<data.length; i++){
        if(data[i].onlinedate === onlinedate && data[i].status === status){
          list.push(data[i])
        }
      }
      this.setState({
        methodList:list
      })
    }
    // onlinedate isapi
    else if(onlinedate && status === null && isapi !== null){
      for(let i=0; i<data.length; i++){
        if(data[i].onlinedate === onlinedate && data[i].isapi === isapi){
          list.push(data[i])
        }
      }
      this.setState({
        methodList:list
      })
    }
    // status isapi
    else if(!onlinedate && status !== null && isapi !== null){
      for(let i=0; i<data.length; i++){
        if(data[i].status === status && data[i].isapi === isapi){
          list.push(data[i])
        }
      }
      this.setState({
        methodList:list
      })
    } else {
      this.setState({
        methodList: this.state.data
      })
    }
  };
  // ^^^^^

  render() {
    // const data = methodList;
    const data = this.state.methodList;
    const self = this;
    const rowSelection = {
      onSelect: (record, selected) => {
        const oldSelecteds = self.state.selectedRowKeys;
        const infCount = self.state.infCount;
        const infKey = record.infKey;
        const infLength = record.infLength;
        let selectedRowKeys = [];
        if (record.isInf) {
          selectedRowKeys = record.children.map(item => item._id).concat(record.key);
          if (selected) {
            selectedRowKeys = selectedRowKeys
              .filter(id => oldSelecteds.indexOf(id) === -1)
              .concat(oldSelecteds);
            infCount[infKey] = infLength;
          } else {
            selectedRowKeys = oldSelecteds.filter(id => selectedRowKeys.indexOf(id) === -1);
            infCount[infKey] = 0;
          }
        } else {
          if (selected) {
            selectedRowKeys = oldSelecteds.concat(record._id);
            if (infCount[infKey]) {
              infCount[infKey] += 1;
            } else {
              infCount[infKey] = 1;
            }
            if (infCount[infKey] === record.infLength) {
              selectedRowKeys.push(infKey);
            }
          } else {
            selectedRowKeys = oldSelecteds.filter(id => id !== record._id);
            if (infCount[infKey]) {
              infCount[infKey] -= 1;
            }
            selectedRowKeys = selectedRowKeys.filter(id => id !== infKey);
          }
        }
        self.setState({ selectedRowKeys, infCount });
        console.log('filter1:', selectedRowKeys.filter(id => ('' + id).indexOf('inf') === -1));
        self.props.selectMethod(
          selectedRowKeys.filter(id => ('' + id).indexOf('inf') === -1),
          self.state.project
        );
      },
      onSelectAll: selected => {
        // console.log(selected, selectedRows, changeRows);
        let selectedRowKeys = [];
        let infCount = self.state.infCount;
        if (selected) {
          data.forEach(item => {
            if (item.children) {
              infCount['inf_' + item._id] = item.children.length;
              selectedRowKeys = selectedRowKeys.concat(item.children.map(item => item._id));
            }
          });
          selectedRowKeys = selectedRowKeys.concat(data.map(item => item.key));
        } else {
          infCount = {};
          selectedRowKeys = [];
        }
        self.setState({ selectedRowKeys, infCount });
        console.log('filter2:', selectedRowKeys.filter(id => ('' + id).indexOf('inf') === -1));
        self.props.selectMethod(
          selectedRowKeys.filter(id => ('' + id).indexOf('inf') === -1),
          self.state.project
        );
      },
      selectedRowKeys: self.state.selectedRowKeys
    };

    const columns = [
      {
        title: '接口类名',
        dataIndex: 'classname',
        width: '25%'
      },
      {
        title: '方法名',
        dataIndex: 'mname',
        width: '20%'
      },
      {
        title: '上线时间',
        dataIndex: 'onlinedate',
        width: '20%'
      },
      {
        title: '是否api',
        dataIndex: 'isapi',
        width: '15%',
        render: text => {
          return (text === 1 ?
              (
                <span>是</span>
              ):(
                <span>否</span>
              ))
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        render: text => {
          return (
              !isNaN(text) &&
            (text === 3 ? (
              <span className="tag-status online">已上线</span>
            ) : (text === 2 ?(
              <span className="tag-status inuat">uat测试</span>
            ) : (text === 1 ?(
              <span className="tag-status insit">sit测试</span>
            ) : (
              <span className="tag-status design">设计中</span>
            )
            )))
          )
        }
      }
    ];

    return (
      <div>
        <div className="select-project">
          <span>选择上线时间： </span>
          <DatePicker
              format={this.dateFormat} onChange={this.handleDateChange}/>
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <span>选择是否api： </span>
          <Select defaultValue={"所有"} onChange={this.handleApiChange}>
            <Option value = {null}>所有</Option>
            <Option value = {1}>是</Option>
            <Option value = {0}>否</Option>
          </Select>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <span>选择状态： </span>
          <Select defaultValue={"所有状态"} onChange={this.handleStatusChange}>
            <Option value = {null}>所有状态</Option>
            <Option className="tag-status design" value = {0}>设计中</Option>
            <Option className="tag-status insit" value = {1}>sit测试</Option>
            <Option className="tag-status inuat" value = {2}>uat测试</Option>
            <Option className="tag-status online" value = {3}>已上线</Option>
          </Select>
          <Button
              style={{ float: 'right' }}
              type="primary"
              onClick={this.handleSearch}
          >
            筛选
          </Button>
        </div>
        <Table columns={columns} rowSelection={rowSelection} dataSource={data} pagination={true} />
      </div>
    );
  }
}
